package com.amazon.web.controller;
import com.amazon.bo.*;
import com.amazon.bo.User;
import com.amazon.bo.UserSession;
import com.amazon.bo.enums.UserStatusEnum;
import com.amazon.bo.enums.UserType;
import com.amazon.service.*;
import com.amazon.web.controller.vo.ClientEunm;
import com.amazon.web.model.account.LoginResult;
import com.amazon.web.util.*;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.amazon.web.model.account.LoginResult;

import java.io.ByteArrayInputStream;
import java.io.Console;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.amazon.web.util.EncryptionUtil;
import org.xml.sax.SAXException;

import javax.annotation.Resource;
import javax.xml.parsers.ParserConfigurationException;

/**
 * Created by anhui on 2018/1/3.
 */
@RestController
@RequestMapping(value="user")
public class UserController {

    @Value("${is.open.cms}")
    public String isOpenCms;


    @Resource
    private OSSManageUtil ossManageUtil;

    @Resource
    UserService userService;

    @Autowired
    I18nService i18nService;

    @Autowired
    ProductService productService;

    @Autowired
    OrdersService ordersService;

    @Autowired
    ShopService shopService;

    @RequestMapping(value="login",method =RequestMethod.GET)
    public Map<String,Object> login(String username , String pwd){




        Map<String,Object> result = new HashMap<>();
        if(username!=null && username.length()>0 && pwd!=null && pwd.length()>0 ){
            Map<String,Object> pms=new HashMap<>();
            pms.put("username",username);
            pms.put("pwd", EncryptionUtil.SHA256(pwd));
            result=userService.login(pms);
            if(result!=null && result.containsKey("username")){

                LoginResult loginResult = getLoginResult(username, pwd, "ADMIN", "zh", 86);

                result.put("user",loginResult);
                result.put("wx","");

                result.put("flag","success");
            }
            else {
                result.put("flag","error_wrong");
            }
            return result;
        }
        else {
            result.put("flag","error_null");
        }
        return null;
    }

    @RequestMapping(value="getPuserList",method =RequestMethod.GET)
    public ApiListResponse getAdminList(int page,int pagesize) {
        List<User> list = userService.getUserList(UserType.ADMIN, page, pagesize);
        return ResponseUtil.getSuccessResponse(list, 3);
    }

    @RequestMapping(value="shopuseradd",method =RequestMethod.POST)
    public Object shopuseradd(User u){
        u.setUserType(UserType.USER);
        userService.saveUser(u);
        return "";
    }
    @RequestMapping(value="getshopuserList",method =RequestMethod.GET)
    public ApiListResponse getshopuserList(int page,int pagesize) {
        List<User> list = userService.getShopUserList(UserType.USER,"", page, pagesize);
        return ResponseUtil.getSuccessResponse(list, 3);
    }

    @RequestMapping(value = "/test1", method = RequestMethod.GET)
    public Object testAmazon() throws Exception {

        return  Tools.parserJson2Map(SignatureUtil.getOrderItemList("205-3936607-2790718",new Shop()));

       // return SignatureUtil.updateProduct("");
    }

    @RequestMapping(value = "/orders", method = RequestMethod.GET)
    public Object orders() throws Exception {

        Shop shop = shopService.getById(Long.parseLong("7"));
        String orders = SignatureUtil.getOrder(shop);

        Map<String,Object> orderMap=Tools.parserJson2Map(orders);


        List<Map<String,Object>> orderList =(List<Map<String,Object>>)((Map<String,Object>)((Map<String,Object>)orderMap.get("ListOrdersResult")).get("Orders")).get("Order");

        for(Map<String,Object> order :orderList){

            String orderStatus=order.get("OrderStatus").toString();
            if(!orderStatus.equals("Canceled")){

                Map<String,Object> shippingAddress =(Map<String,Object>)order.get("ShippingAddress");
                order.put("StateOrRegion",shippingAddress.get("StateOrRegion"));
                order.put("AddressLine1",shippingAddress.get("AddressLine1"));
                order.put("PostalCode",shippingAddress.get("PostalCode"));
                order.put("City",shippingAddress.get("City"));
                order.put("AddressType",shippingAddress.get("AddressType"));
                order.put("CountryCode",shippingAddress.get("CountryCode"));
                order.put("Name",shippingAddress.get("Name"));


                Map<String,Object> orderTotal =(Map<String,Object>)order.get("OrderTotal");
                order.put("CurrencyCode",orderTotal.get("CurrencyCode"));
                order.put("Amount",orderTotal.get("Amount"));

                Map<String,Object> paymentMethodDetails =(Map<String,Object>)order.get("PaymentMethodDetails");
                order.put("PaymentMethodDetail",paymentMethodDetails.get("PaymentMethodDetail"));


                Orders od= new Orders();
                od.setAmazonOrderId(order.get("AmazonOrderId").toString());
                od.setOrderBody(com.alibaba.fastjson.JSON.toJSONString(order));

                ordersService.addOrders(od);
            }
        }


        return orderMap;



        //return SignatureUtil.updateProduct("");
    }

    private LoginResult getLoginResult(String username, String password, String from,String lang,Integer countryCode) {
        if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
            throw new RuntimeException(i18nService.getMessage("" + 104, lang));
        }

        if (ClientEunm.ADMIN.name().equals(from)) {
            countryCode = 86;
        }

        if (countryCode == null) {
            throw new RuntimeException(i18nService.getMessage("" + 116, lang));
        }

        User user = userService.getUserByUsername(username);

        if (user == null) {
            throw new RuntimeException(i18nService.getMessage("" + 105, lang));
        }
        if (!user.getPasswordHash().equals(EncryptionUtil.SHA256(password))) {
            throw new RuntimeException(i18nService.getMessage("" + 106, lang));
        }
        if (user.getUserStatus() == UserStatusEnum.INVALID) {
            throw new RuntimeException(i18nService.getMessage("" + 107, lang));
        }

        //user.setLonginIp(getIpAddr(request));
        user.setLonginNum(user.getLonginNum() + 1);
        userService.updateUser(user);


        UserSession userSession = userService.createUserSession(user.getId());
        LoginResult loginResult = getLoginResultFrom(user, from);
        loginResult.setToken(userSession.getToken());
        loginResult.setMsg_count(0);

        loginResult.setIsSign(1);
        return loginResult;
    }
    private LoginResult getLoginResultFrom(User user, String from) {
        LoginResult loginResult = new LoginResult();


        //loginResult.setType(user.getUserType().ordinal());
        loginResult.setUsername(user.getMobile());
        loginResult.setId(user.getId());
        loginResult.setAvatar(user.getAvatar());
        loginResult.setNickname(user.getNickname());
        //loginResult.setAddress(user.getAddress());
       // loginResult.setSignature(user.getSignature());
        loginResult.setPhone_number(user.getMobile());
        loginResult.setRealname(user.getRealName());
        loginResult.setCity_id(user.getAreaId());


        Calendar calendar = Calendar.getInstance();
        calendar.setTime(DateUtil.getCurrentDate());
        calendar.add(Calendar.DATE, -1);


        loginResult.setLanguage(user.getUserLanguage());
        loginResult.setCountry_code(user.getCountryCode());

        return loginResult;
    }


    @RequestMapping(value = "/textProduct", method = RequestMethod.GET)
    public Object test() throws InterruptedException, IOException, SAXException, ParserConfigurationException {
//    @RequestMapping(value = "/test", method = RequestMethod.GET)
//    public Object test() throws InterruptedException {

        //String uri="https://www.chinabrands.com/item/dropship-wkae-flowers-embossing-pattern-pu-leather-flip-stand-case-cover-for-htc-u11-2272482-p.html?goods_id=340725&wid=1";

        //createSku(uri);

        String condation="&min_stock=4&max_stock=100";
        String targetUrl = "https://www.chinabrands.cn/c-872_page";
        String url = "https://www.chinabrands.cn/c-872.html?min_stock=4&max_stock=100";

        List<String> ursl = new ArrayList<>();

        String html = HttpUtil.get(url);

        // 按指定模式在字符串查找
        String pattern = "<a class=\"js-href-seo\"[\\w|\\d\\s|=|/|\\-|.|&|;\"]+>[\\d||末页|Last]+</a>";


        // 创建 Pattern 对象
        Pattern r = Pattern.compile(pattern);
        // 现在创建 matcher 对象
        Matcher m = r.matcher(html);


        Pattern rr = Pattern.compile("sid=[\\d]+");
        Matcher mm = rr.matcher(html);

        String sid = "";
        if (mm.find()) {
            sid = mm.group();
        }
        sid=sid+condation;


        while (m.find()) {

            String value = m.group();
            // 提取链接
            String p = "href=[\\w|\\d\\s|=|/|\\-|.|\"]+.html";
            Pattern pValue = Pattern.compile(p);
            Matcher mUrl = pValue.matcher(value);


            while (mUrl.find()) {
                String href = mUrl.group().replace("href=\"", "https://www.chinabrands.com");// + "?" + sid;
                ursl.add(href);
            }
        }

        // 获取总页数
        String maxPageSize = ursl.get(ursl.size() - 1);
        pattern = "[\\d]+.html";
        r = Pattern.compile(pattern);
        m = r.matcher(maxPageSize);

        while (m.find()) {
            maxPageSize = m.group().replace(".html", "");
        }

        List<String> targetPage = new ArrayList<>();
        for (int i = 0; i < Integer.parseInt(maxPageSize); i++) {

            targetPage.add(targetUrl + (i + 1) + ".html"+"?"+sid);
        }


        List<String> goodsList = new ArrayList<>();
        for (int i = 0; i < targetPage.size(); i++) {

            String categoryUrl = targetPage.get(i);

            String htmlCode = HttpUtil.get(categoryUrl);


            pattern = "<a href=\"https://www.chinabrands.cn/item/[\\w|\\d\\s|=|/|\\-|.|&\"]+>";
            r = Pattern.compile(pattern);
            m = r.matcher(htmlCode);

            while (m.find()) {

                String goodsUrl=m.group().substring(0, m.group().indexOf(".html")) + ".html";
                goodsUrl=goodsUrl.replace("<a href=\"","");
                goodsList.add(goodsUrl);

            }

            long l = 1000;
            Thread.sleep(l);
        }

        List<String> skuList= new ArrayList<>();
        int i=0;
        for(String skuUrl:goodsList){

            i++;


            String detailHtml=HttpUtil.get(skuUrl);


            pattern = "data-url=\"https:[\\w|\\d\\s|=|/|\\-|.|&|?\"]+";
            r = Pattern.compile(pattern);
            m = r.matcher(detailHtml);

            String skuHref="";
            if(m.find()){
                skuHref=m.group().replace("data-url=\"","").replace("\"","");
                skuList.add(skuHref);
            }

            long l = 1000;
            Thread.sleep(l);
            createSku(detailHtml,skuUrl);
        }

        goodsList.addAll(skuList);



        // 产品列表
        int j=0;
        for (String goodsUrl : skuList) {

            j++;

            String detailHtml=HttpUtil.get(goodsUrl);

            createSku(detailHtml,goodsUrl);

        }


        return null;
    }

    private void createSku(String detailHtml,String url) throws ParserConfigurationException, IOException, SAXException {

        Product product  = new Product();

        product.setSkuUrl(url);

        String prifix="AMAZON";

        String pattern;
        Pattern r;
        Matcher m;
        //String detailHtml =detailHtml; //HttpUtil.get(goodsUrl);

        // 1 sku
        pattern = "<span class=\"fb\">SKU:</span>[\\d]+";
        r = Pattern.compile(pattern);
        m = r.matcher(detailHtml);

        String SKU="";
        if(m.find()){
            SKU=m.group().replace("<span class=\"fb\">SKU:</span>","");
            SKU=prifix+SKU;
        }
        product.setSKU(SKU);

        // 2 StandardProductID
        String StandardProductID="";
        product.setStandardProductID(StandardProductID);

        // 3 ProductTaxCode 欧洲不需要
        String ProductTaxCode="";
        product.setProductTaxCode(ProductTaxCode);

        // 4 LaunchDate 能浏览
        String LaunchDate=null;
        product.setLaunchDate(LaunchDate);

        // 5 ReleaseDate 能售卖
        String ReleaseDate=null;
       product.setReleaseDate(ReleaseDate);

        // 6 Condition
        String Condition="New";
        product.setConditions(Condition);

        // 7 Rebate
        String Rebate=null;
        //product.setRe

        // 8 ItemPackageQuantity
        String ItemPackageQuantity="1";
        product.setItemPackageQuantity(Integer.parseInt(ItemPackageQuantity));

        // 9 NumberOfItems
        String NumberOfItems="1";
        product.setNumberOfItems(Integer.parseInt(NumberOfItems));


        // 10 DescriptionData

        // 10.1 Title

        pattern = "<h3 class=\"goods-title(.*)>\\n(.*)</h3>";
        r = Pattern.compile(pattern);
        m = r.matcher(detailHtml);

        String Title="";
        if(m.find()){
            Title=m.group(2).replace("</h3>","").replace("\"","");
        }
        product.setTitle(Title);

        //10.2 Brand 品牌
        String Brand=null;
        product.setBrand(Brand);

        //10.3 Designer  设计师
        product.setDesigner("zhou");

        //10.4 Description 产品描述

        pattern = "<div class=\"xxkkk2\">(.*)</div>";
        r = Pattern.compile(pattern);
        m = r.matcher(detailHtml);

        String Description="";
        if(m.find()){
            Description=m.group().replace("<div class=\"xxkkk2\">","").replace("</div>","");
        }
        Description=Description.replace("<","&lt;").replace(">","&gt;");
        product.setDescription(Description);



        //10.5 BulletPoint 公告
        product.setBulletPoint("");

        //10.6 ItemDimensions 长宽高
        product.setItemDimensions("");

        //10.7 PackageDimensions 包裹长宽高

        pattern = "<strong>Package size[\\s|\\(|\\)|\\w|\\:|<|>|\\/|.]+[\\s]\n";
        r = Pattern.compile(pattern);
        m = r.matcher(detailHtml);

        String PackageDimensions="";
        if(m.find()){
            PackageDimensions=m.group().replace("<strong>Package size (L x W x H):</strong>","");
        }
        PackageDimensions=PackageDimensions.replace("<","&lt;").replace(">","&gt;");
        product.setPackageDimensions(PackageDimensions);


        //10.8 PackageWeight 包装重量


        //10.9 ShippingWeight 运输重量
        pattern = "<strong>Package weight[\\s|\\(|\\)|\\w|\\:|<|>|\\/|.]+<br />";
        r = Pattern.compile(pattern);
        m = r.matcher(detailHtml);

        String ShippingWeight="";
        if(m.find()){
            ShippingWeight=m.group().replace("<strong>Package weight:</strong>","").replace("<br />","");
        }
        ShippingWeight=ShippingWeight.replace("<","&lt;").replace(">","&gt;");
        product.setShippingWeight(ShippingWeight);

        //10.10 MerchantCatalogNumber 卖家商品目录

        //10.11 MSRP 建议零售价

        pattern = "<meta property=\"product:price:amount\" content=\"[\\d|.]+";
        r = Pattern.compile(pattern);
        m = r.matcher(detailHtml);

        String MSRP="";
        if(m.find()){
            MSRP=m.group().replace("<meta property=\"product:price:amount\" content=\"","");
        }
        product.setMSRP(MSRP);

        //10.12 MaxOrderQuantity 每单可购买数量

        //10.13 SerialNumberRequired 是否需要序列号

        //10.14 Prop65

        //10.15 LegalDisclaimer 免责声明

        //10.16 Manufacturer 制造商

        //10.17 MfrPartNumber 原制造商提供的零件号

        //10.18 SearchTerms 搜素关键字

        //10.19 PlatinumKeywords

        //10.20 RecommendedBrowseNode

        //10.21 Memorabilia 纪念品

        //10.22 Autographed 亲笔签名

        //10.23 UsedFor 欧洲不使用

        //10.24 ItemType 项目类型

        //10.25 OtherItemAttributes 其它属性

        //10.26 TargetAudience 受众

        //10.27 SubjectContent 主题内容

        //10.28 IsGiftWrapAvailable 礼品包装

        //10.29 IsGiftMessageAvailable 礼品描述

        //10.30 MaxAggregateShipQuantity 同一个包裹可以运送多少个商品

        // 图片 data-original=(.*)\n(.*)data-big-url=(.*)

        pattern = "data-original=(.*)\\n(.*)data-big-url=(.*)";
        r = Pattern.compile(pattern);
        m = r.matcher(detailHtml);

        String smallImg="";
        String bigImg="";
        while(m.find()){
            smallImg+=m.group(1).replace("\"","")+",";
            bigImg+=m.group(3).replace("\"","")+",";
        }
        product.setSmallImgs(smallImg);
        product.setBigImg(bigImg);
        product.setCategoryName("宠物用品");

        productService.addProduct(product);

    }


}
